package me.project.jobster.common.util;

import java.security.MessageDigest;
import java.util.Objects;

/**
 * @author mbryce
 * @date 2018/4/21
 */
public class MD5Utils {
    private static final String ALGORITHM_MD5 = "MD5";
    private static final String UTF_8 = "UTF-8";

    private MD5Utils() { }

    /**
     * MD5 16bit 小写.
     * @param readyEncryptStr ready encrypt string
     * @return String encrypt result string
     * @throws
     * */
    public static String md5Bit16Lower(String readyEncryptStr) {
        if (Objects.nonNull(readyEncryptStr)) {
            return Objects.requireNonNull(MD5Utils.md5Bit32Lower(readyEncryptStr)).substring(8, 24);
        } else {
            return null;
        }
    }

    /**
     * MD5 16bit 大写.
     * @param readyEncryptStr ready encrypt string
     * @return String encrypt result string
     * @throws
     * */
    public static String md5Bit16Upper(String readyEncryptStr) {
        return Objects.requireNonNull(md5Bit16Lower(readyEncryptStr)).toUpperCase();
    }

    /**
     * MD5 32bit 小写.
     * @param readyEncryptStr ready encrypt string
     * @return String encrypt result string
     * @throws
     * */
    public static String md5Bit32Lower(String readyEncryptStr) {
        if (Objects.nonNull(readyEncryptStr)) {
            MessageDigest md = null;
            try {
                md = MessageDigest.getInstance(ALGORITHM_MD5);
                md.update(readyEncryptStr.getBytes(UTF_8));
                byte[] b = md.digest();
                StringBuilder su = new StringBuilder();
                for (byte aB : b) {
                    String haxHex = Integer.toHexString(aB & 0xFF);
                    if (haxHex.length() < 2) {
                        su.append("0");
                    }
                    su.append(haxHex);
                }
                return su.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        } else {
            return null;
        }
    }

    /**
     * MD5 32bit 大写.
     * @param readyEncryptStr ready encrypt string
     * @return String encrypt result string
     * @throws
     * */
    public static String md5Bit32Upper(String readyEncryptStr) {
        return Objects.requireNonNull(md5Bit32Lower(readyEncryptStr)).toUpperCase();
    }

}

